import { Component, OnInit } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { DatePipe } from '@angular/common';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import * as moment from 'moment';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { Workbook } from "exceljs";




@Component({
  selector: 'app-beipinmsg',
  templateUrl: './beipinmsg.component.html',
  styleUrls: ['./beipinmsg.component.scss'],
  providers: [DatePipe]
})
export class BeipinmsgComponent implements OnInit {
  isShow; // 新增
  isVisible = false; // 删除
  liaohao = ''; // 查询输入的料号
  listOfData;
  editCache = {};
  material_no; // 料号
  name; // 名称
  unit; // 单位
  shelf_position; // 价位
  type; // 类别
  safe_stock; // 安全库存
  remark; // 备注

  lydata; // 领用数组
  short = []; // 缺料数量
  downList; // 下载列表
  obj = []; // 存放料号、缺料数量


  constructor(
    public axios: AxiosService,
    private datePipe: DatePipe,
    private storage: LocalStorageService,
  ) { }

  ngOnInit(): void {
    this.getData();
    // this.getlydata();
    this.getDownListData();
  }

  // 查询信息
  getData() {
    let type = []; // 保存类别和料号到本地
    // debugger
    if (this.liaohao === '') {
      console.log(this.liaohao)
      this.axios.axiosPost('QueryBaseMaterial')
        .then((data) => {
          if (data) {
            console.log(data);
            this.listOfData = data['order'];
            for (let i = 0; i < this.listOfData.length; i++) {
              type.push({
                material_no: this.listOfData[i].material_no,
                type: this.listOfData[i].type
              })
              this.editCache[i] = { edit: true, isdel: true, data: this.listOfData[i] };
            }
            this.storage.setStorageData('data', type);
            // console.log(type)
            // console.log(this.listOfData);
            // console.log(this.editCache);
          }
        })
        .catch((err) => {
          console.log(err);
        })
    } else {
      this.axios.axiosPost('QueryBaseMaterial', { keyword: this.liaohao })
        .then((data) => {
          if (data) {
            console.log(data);
            this.listOfData = data['order'];
            for (let i = 0; i < this.listOfData.length; i++) {
              this.editCache[i] = { edit: true, isdel: true, data: this.listOfData[i] };
            }
            console.log(this.listOfData);
            console.log(this.editCache);
          }
        })
        .catch((err) => {
          console.log(err);
        })
    }
  }

  // 修改信息
  startEdit(key: number): void {
    console.log(key)
    console.log(this.editCache[key])
    console.log(this.editCache[key]['data'].material_no)
    this.editCache[key].isdel = false;
    this.editCache[key].edit = false;
  }
  // 保存修改
  saveEdit(key: number): void {
    debugger
    console.log(this.editCache[key]['data'].remark)
    this.editCache[key].isdel = true;
    this.editCache[key].edit = true;
    this.axios.axiosPost('AddBaseMaterial', {
      material_no: this.editCache[key]['data'].material_no,
      name: this.editCache[key]['data'].name,
      unit: this.editCache[key]['data'].unit,
      shelf_position: this.editCache[key]['data'].shelf_position,
      type: this.editCache[key]['data'].type,
      safe_stock: this.editCache[key]['data'].safe_stock,
      remark: this.editCache[key]['data'].remark
    })
      .then((data) => {
        if (data['result'] === 'ok') {
          console.log(data)
          this.getData();
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }
  // 撤销修改
  cancelEdit(key: number): void {
    // debugger
    // const index = this.listOfData.findIndex((item, index) => index === key);
    // this.editCache[key] = {
    //   data: { ...this.listOfData },
    //   edit: true,
    //   isdel: true
    // };
    this.getData();
  }

  // 新增
  showinput() {
    this.isShow = true;
    this.material_no = '';
    this.name = '';
    this.unit = '';
    this.shelf_position = '';
    this.type = '';
    this.remark = '';
    this.safe_stock = '';
  }
  // 判断料号是否存在，若已存在读取信息到input中
  pushLiaohao() {
    for (let i = 0; i < this.listOfData.length; i++) {
      if (this.material_no === this.listOfData[i]['material_no']) {
        this.name = this.listOfData[i]['name']
        this.unit = this.listOfData[i]['unit']
        this.shelf_position = this.listOfData[i]['shelf_position']
        this.type = this.listOfData[i]['type']
        this.remark = this.listOfData[i]['remark']
        this.safe_stock = this.listOfData[i]['safe_stock']
      }
    }
  }
  // 确认新增
  confirmAdd() {
    // debugger
    if (this.material_no !== '') {
      this.axios.axiosPost('AddBaseMaterial', {
        material_no: this.material_no,
        name: this.name,
        unit: this.unit,
        shelf_position: this.shelf_position,
        type: this.type,
        safe_stock: this.safe_stock,
        remark: this.remark
      })
        .then((data) => {
          console.log(data)
          if (data['result'] === 'ok') {
            console.log(data)
            this.getData();
          }
        })
        .catch((err) => {
          console.log(err);
        })
      this.isShow = false;
    } else {
      alert('料號不能為空');
    }
  }
  // 取消新增
  cancelAdd() {
    this.isShow = false;
  }

  // 删除
  showModal(item): void {
    this.material_no = item.material_no;
    console.log(this.material_no);
    this.isVisible = true;
  }
  handleOk() {
    this.isVisible = false;
    // debugger
    this.axios.axiosPost('DeleteBaseMaterial', { 'material_no': this.material_no })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.getData();
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }
  handleCancel(): void {
    this.isVisible = false;
  }

  // 获取领用明细中的需求总量-已备数量 => 缺料数量
  // getlydata() {
  //   // debugger
  //   let array = [];
  //   this.axios.axiosPost('QueryBaseMaterial', { 'name': 1 })
  //     .then((data) => {
  //       if (data) {
  //         this.downList = data['order'];
  //         console.log(this.downList)
  //       }
  //     })
  //     .catch((err) => {
  //       console.log(err);
  //     });
  //   this.axios.axiosPost('QueryMaterialSend')
  //     .then((data) => {
  //       if (data['result'] == 'ok') {
  //         this.lydata = data['order'];
  //         // console.log(this.lydata);
  //         for (let i = 0; i < this.lydata.length; i++) {
  //           // 需求总量 - 已备 > 0   需购  缺料数量 = 需求总量 - 已备
  //           // 需求总量 - 已备 <= 0  否    缺料数量 = 0
  //           if (Number(this.lydata[i].quatity_total) - Number(this.lydata[i].yibei_shuliang) <= 0) {
  //             this.lydata[i].queliao = 0;
  //             // this.lydata[i].isBuy = '否'
  //           } else {
  //             this.lydata[i].queliao = Number(this.lydata[i].quatity_total) - Number(this.lydata[i].yibei_shuliang);
  //             // this.lydata[i].isBuy = '是'
  //           }
  //         }
  //         if (array.length = 0) {
  //           array.push(this.lydata[0])
  //         } else {
  //           for (let a = 0; a < array.length; a++) {
  //             for (let i = 0; i < this.lydata.length; i++) {
  //               if (array[a].material_no != this.lydata[i].material_no) {
  //                 array.push(this.lydata[i]);
  //               } else if (array[a].material_no == this.lydata[i].material_no) {
  //                 array[a].queliao += this.lydata[i].queliao;
  //               }
  //             }
  //           }
  //         }
  //         console.log(this.lydata)
  //       }
  //     })
  //     .catch((err) => {
  //       console.log(err);
  //     })
  // }

  getDownListData() {
    this.axios.axiosPost('QueryBaseMaterial', { 'name': 1 })
      .then((data) => {
        if (data) {
          this.downList = data['order'];
          console.log(this.downList)
          this.axios.axiosPost('QueryMaterialSend')
            .then((data) => {
              if (data['result'] == 'ok') {
                this.lydata = data['order'];
                console.log(this.lydata);
                // for (let i = 0; i < this.lydata.length; i++) {
                //   // 需求总量 - 已备 > 0   需购  缺料数量 = 需求总量 - 已备
                //   // 需求总量 - 已备 <= 0  否    缺料数量 = 0
                //   if (Number(this.lydata[i].quatity_total) - Number(this.lydata[i].yibei_shuliang) <= 0) {
                //     this.lydata[i].queliao = 0;
                //     // this.lydata[i].isBuy = '否'
                //   } else {
                //     this.lydata[i].queliao = Number(this.lydata[i].quatity_total) - Number(this.lydata[i].yibei_shuliang);
                //     // this.lydata[i].isBuy = '是'
                //   }
                // }
                // for (let i = this.lydata.length - 1; i > 0; i--) {
                //   // console.log(this.lydata[i].material_no)
                //   if (this.lydata[i].material_no == this.lydata[i - 1].material_no) {
                //     this.lydata[i - 1].queliao += this.lydata[i].queliao;
                //     this.lydata.splice([i], 1);
                //   }
                // }
                // for (let i = 0; i < this.lydata.length; i++) {
                //   for (let j = 0; j < this.downList.length; j++) {
                //     if (this.lydata[i].material_no == this.downList[j].material_no) {
                //       this.lydata[i].yibei_shuliang+=this.downList[j].
                //   }
                // }
                for (let i = 0; i < this.downList.length; i++) {
                  this.downList[i].yibei_shuliang = 0;
                  this.downList[i].quatity_total = 0;
                  for (let j = 0; j < this.lydata.length; j++) {
                    if (this.downList[i].material_no == this.lydata[j].material_no) {
                      this.downList[i].yibei_shuliang += Number(this.lydata[j].yibei_shuliang)
                      this.downList[i].quatity_total += Number(this.lydata[j].quatity_total);
                    }
                  }
                  if (Number(this.downList[i].yibei_shuliang) + Number(this.downList[i].stock) < Number(this.downList[i].quatity_total)) {
                    this.downList[i].isBuy = '是';
                    this.downList[i].queliao = this.downList[i].quatity_total - Number(this.downList[i].yibei_shuliang) - Number(this.downList[i].stock)
                    console.log(this.downList[i].queliao);
                  } else if (Number(this.downList[i].stock) < Number(this.downList[i].safe_stock)) {
                    this.downList[i].isBuy = '是';
                    this.downList[i].queliao = Number(this.downList[i].safe_stock) - Number(this.downList[i].stock)
                  } else {
                    this.downList[i].isBuy = '否';
                    this.downList[i].queliao = 0;
                  }
                  // if (Number(this.downList[i].queliao) > 0) {
                  //   this.downList[i].isBuy = '是';
                  // } else if (Number(this.downList[i].stock) < Number(this.downList[i].safe_stock)) {
                  //   this.downList[i].isBuy = '是';
                  // } else {
                  //   this.downList[i].isBuy = '否';
                  // }

                }
                console.log(this.lydata)
                console.log(this.downList);
              }
            })
            .catch((err) => {
              console.log(err);
            })
        }
      })
      .catch((err) => {
        console.log(err);
      });

  }

  // 下载入库成功的数据
  downLoad() {
    console.log(this.downList);

    this.axios.axiosPost('AddDownloadCount')
      .then((data) => {
        console.log(data)
      })
      .catch((err) => {
        console.log(err);
      });
    let exportlist = [];
    if (this.downList.length == 0) {
      alert('暫無數據');
    } else {
      for (let i = 0; i < this.downList.length; i++) {
        exportlist.push({
          '料號': this.downList[i].material_no,
          '名稱': this.downList[i].name,
          '安全庫存': this.downList[i].safe_stock,
          '類別': this.downList[i].type,
          '架位': this.downList[i].shelf_position,
          '單位': this.downList[i].unit,
          '現有庫存': this.downList[i].stock,
          '缺料數量': this.downList[i].queliao,
          '是否需購': this.downList[i].isBuy,
          '前2個月': this.downList[i].previous2month,
          '前1個月': this.downList[i].previousmonth,
          '當月': this.downList[i].currentmonth,
          '未稅總價': Number(this.downList[i].cost).toFixed(2)
        });
      }
      console.log(exportlist);
      this.downList = [];
      exportlist.forEach((row: any) => {
        this.downList.push(Object.values(row))
      })
      let head = ["料號", "名稱", "安全庫存", "類別", "架位", "單位", "現有庫存", "缺料數量", "是否需購", "前2個月", "前1個月", "當月", "未稅總價"]
      let reportData = {
        title: '庫存狀況',
        headers: head,
        data: this.downList,
      };
      this.saveAsExcelFile(reportData);
    }
  }
  private saveAsExcelFile(excelData) {
    const title = excelData.title;
    const header = excelData.headers;
    const data = excelData.data;

    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet("庫存狀況");
    const headerRow = worksheet.addRow(header);
    const worksheet1 = workbook.getWorksheet(1);
    console.log(worksheet1);

    headerRow.eachCell((cell) => {
      cell.fill = {
        type: "pattern",
        pattern: "solid",
        // 设置表头背景颜色
        fgColor: { argb: "FFFFFF" },
      };
      cell.alignment = { vertical: "middle", horizontal: "center" };
      cell.font = {
        bold: true,
        // 设置表头的字体颜色
        color: { argb: "000000" },
        size: 12,
      };
      cell.border = {
        // 设置边框粗细
        top: { style: "thin" },
        left: { style: "thin" },
        bottom: { style: "thin" },
        right: { style: "thin" },
      };
    });
    // 设置表格内容居中对齐
    const contentarray = [];
    data.forEach((ele) => {
      contentarray.push(worksheet.addRow(ele));
    });
    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < contentarray.length; i++) {
      contentarray[i].eachCell((cell) => {
        cell.border = {
          // 设置边框粗细
          top: { style: "thin" },
          left: { style: "thin" },
          bottom: { style: "thin" },
          right: { style: "thin" },
        };
        cell.fill = {
          type: "pattern",
          pattern: "solid",
          // 设置表头背景颜色
          fgColor: { argb: "FFFFFF" },
        };
        cell.alignment = { vertical: "middle", horizontal: "center" };
      });
    }

    worksheet.getColumn(1).width = 16;
    worksheet.getColumn(2).width = 70;
    worksheet.getColumn(3).width = 10;
    worksheet.getColumn(4).width = 16;
    worksheet.getColumn(5).width = 16;
    worksheet.getColumn(6).width = 10;
    worksheet.getColumn(7).width = 21;
    worksheet.getColumn(8).width = 10;
    worksheet.getColumn(9).width = 10;
    worksheet.getColumn(10).width = 10;
    worksheet.getColumn(11).width = 10;
    worksheet.getColumn(12).width = 10;
    worksheet.getColumn(13).width = 15;

    workbook.xlsx.writeBuffer().then((result) => {
      const blob = new Blob([result], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
      });
      FileSaver.saveAs(blob, title + "_" + moment().format("YYYYMMDDHHmmss") + ".xlsx");
    });
  }

  // 去重
  unique(arr: any) {
    var array = [];
    for (var i = 0; i < arr.length; i++) {
      if (array.indexOf(arr[i]) === -1) {
        array.push(arr[i])
      }
    }
    return array;
  }

}
